<?php
/**
 * Created by PhpStorm.
 * User: k
 * Date: 2021/8/9
 * Time: 13:04
 */

namespace app\api\logic;

use Think\Db;

class ScheduleLogic
{
    /**
     * 列表
     * @param $user_id
     * @param $get
     * @param $page
     * @param $size
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function getList($get, $page, $size)
    {
        $where = [];
        $where[] = ['del', '=', 0];
        $where[] = ['is_show', '=', 0];

//        // 分类筛选
//        if (isset($get['label']) && $get['label']) {
//            $where[] = ['label', '=', $get['label']];
//        }
        // 谁的档期
        if (isset($get['host_id']) && $get['host_id']) {
            $where[] = ['host_id', '=', $get['host_id']];
        }

        // 预期数量
        if (isset($get['expect_num']) && $get['expect_num']) {
            $where[] = ['expect_num', '<', $get['expect_num']];
        }
        // 预期佣金比例
        if (isset($get['expect_commission']) && $get['expect_commission']) {
            $where[] = ['expect_commission', '<', $get['expect_commission']];
        }
        // 直播平台
        if (isset($get['platform']) && $get['platform']) {
            $where[] = ['platform', '=', $get['platform']];
        }

        // 预期播出时长(小时h)
        if (isset($get['live_len']) && $get['live_len']) {
            $where[] = ['live_len', '=', $get['live_len']];
        }
        // 直播类型
        if (isset($get['live_type']) && $get['live_type']) {
            $where[] = ['live_type', '=', $get['live_type']];
        }
        //分类筛选
        if (isset($get['label']) && $get['label']) {
            $where[] = ['label', 'like', '%' . $get['label'] . '%'];
        }


        $schedule_count = Db::name('schedule')
            ->where($where)
            ->count();

        $schedule_list = Db::name('schedule')
            ->field('*')
            ->where($where)
            ->page($page, $size)
            ->select();
        $more = is_more($schedule_count, $page, $size);  //是否有下一页

        $data = [
            'list' => $schedule_list,
            'page_no' => $page,
            'page_size' => $size,
            'count' => $schedule_count,
            'more' => $more
        ];
        return $data;
    }


    /**
     * 详情（关联订单）
     * @param $user_id
     * @param $id
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function getDetailOrder($user_id, $id)
    {
        if (!empty($id)) {
            $orders = Db::name("order")->where(["schedule_id" => $id])->where(["user_id" => $user_id])->whereOr(["supplier_id" => $user_id])->select();
            return $orders;
        }
        return [];

    }

    /**
     * 添加档期
     * @param $user_id
     * @param $post
     * @return bool|false|int|string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function add($user_id, $post)
    {
        try {
            Db::startTrans();
            $schedule = [
                "host_id" => $user_id,
                "schedule_sn" => create_schedule_sn(),
                "schedule" => date("Y-m-d", $post['schedule'] / 1000),
                "platform" => isset($post['platform']) ? $post['platform'] : "",
                "is_show" => isset($post['is_show']) ? intval($post['is_show']) : 0,
                "live_type" => isset($post['live_type']) ? $post($post['live_type']) : 0,
                "schedule_type" => isset($post['schedule_type']) ? $post['schedule_type'] : 1,
                "basis_id" => isset($post['basis_id']) ? intval($post['basis_id']) : "",
                "basis_studio_id" => isset($post['basis_studio_id']) ? intval($post['basis_studio_id']) : "",
                "basis_studio_interval_id" => isset($post['basis_studio_interval_id']) ? intval($post['basis_studio_interval_id']) : "",
                "arrive_time" => isset($post['arrive_time']) ? intval($post['arrive_time']) / 1000 : "",
                "staffing" => $post['staffing'] ? json_encode($post['staffing'], true) : json_encode([]),
                "address_id" => isset($post['address_id']) ? intval($post['address_id']) : "",
                "create_time" => time()
            ];

            $schedule_id = Db::name("schedule")->insertGetId($schedule); // 生成档期

            Db::commit();
            return $schedule_id;

        } catch (\Exception $e) {
            Db::rollback();
//            return $e->getMessage();
            return false;
        }
    }

    public static function delSchedule($id)
    {
        return Db::name('schedule')->where("id", $id)->data(["del" => 1])->update();
    }

    public static function updateSchedule($user_id, $post)
    {
        try {
            Db::startTrans();

            $data = [
                'host_id' => $post['host_id'],
                'schedule' => $post['schedule'],
                'label' => $post['label'],
                'expect_num' => intval($post['expect_num']),
                'expect_commission' => intval($post['expect_commission']),
                'platform' => $post['platform'],
                'is_show' => intval($post['is_show']) ?? 0,
                'live_type' => intval($post['live_type']) ?? 0,
                'live_len' => intval($post['live_len']) ?? 1,
                'status' => intval($post['live_type']) ?? 0,
                'update_time' => time()
            ];

            $result = Db::name('schedule')
                ->where(['id' => $post['id'], 'del' => 0])
                ->update($data);

            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return false;
        }

        return $result;
    }

    /**
     * 订单后处理
     * @param $id
     * @param $goods_count
     * @param $sample_price
     * @throws \think\Exception
     * @throws \think\db\exception\DbException
     * @throws \think\exception\PDOException
     */
    public static function orderAfter($id, $data)
    {
        Db::name("schedule")
            ->where("id", $id)
            ->data([
                "goods_count" => $data['goods_count'],
                "sample_price" => $data['sample_price'],
                "basis_use" => $data['basis_use'] ?? 0,
                "basis_staff" => $data['basis_staff'] ?? 0,
            ])
            ->update();
    }

}